import {toLowerCaseKey} from './utils'

export function refreshConnection(proxy){
    proxy.$appStore.setConnectList([])
    proxy.$userIpc.invoke(proxy.$ipcRouters.connectManage.allConnectList, {}).then(res => {
      res.data.forEach(row => {
        proxy.$appStore.pushConnect(row)
      })
    })
    console.log('刷新列表', proxy.$appStore.connectList)
    proxy.$appStore.connectList.forEach(connect=>{
        if(proxy.$appStore.checkConnectOpen(connect)){
        //刷新数据库保留操作状态和表数据
        refreshUsedConnections(proxy,connect)
        refreshUsedDatabase(proxy,connect)
        }
    })
}


/***
 * 刷新当前连接数据库列表
 * */
function refreshUsedConnections(proxy,connect) {
    let channel = '';
    switch (connect.connectId) {
      case 1:
        channel = proxy.$ipcRouters.mysqlMng.showDataBase;
        break;
      default:
        break;
    }
    if (channel.length > 0) {
      proxy.$userIpc.invoke(channel, connect).then(res => {
        if (res.code === 200) {
          let localConnect =proxy.$appStore.usedConnect[connect.id]
          let replaceArray=[]
          res.data.dataList.forEach(item => {
            let obj={}
            Object.keys(item).forEach(key=>{
              obj[key.toLowerCase()] =item[key]
            })
            obj.tableList=[]
            obj.functionList=[]
            obj.viewList=[]
            obj.queryList=[]
            let row =localConnect.usedDatabase.find(row=>row.schema_name===obj.schema_name)
            if(row){
              obj.showTable=row.showTable
              obj.tableList=row.tableList
              obj.functionList=row.functionList
              obj.viewList=row.viewList
              obj.queryList=row.queryList
            }
            replaceArray.push(obj);
          })
          localConnect.usedDatabase=replaceArray
          proxy.$appStore.setUsedConnect(connect.id,localConnect)
        } else {
          proxy.$modal.alertError(res.message)
        }
      })
    } else {
      proxy.$modal.alert("暂不支持此连接！");
    }
  }
  
  function refreshUsedDatabase(proxy,connect) {
    let channel = '';
    switch (connect.connectId) {
      case 1:
        channel = proxy.$ipcRouters.mysqlMng.showDatabaseTables;
        break;
      default:
        break;
    }
    if (channel && channel.length > 0) {
      proxy.$appStore.usedConnect[connect.id].forEach(localUsedConnect=>{
        localUsedConnect.usedDatabase.forEach(localUsedDatabase=>{
          let localConnect = getLocalConnect(connect, localUsedDatabase.schema_name)
          let params={databaseKey:localUsedDatabase.schema_name}
          proxy.$userIpc.invoke(channel, localConnect,params).then(res => {
            if (res.code === 200) {
              localUsedDatabase.tableList=[]
              localUsedDatabase.showTable=true
              Object.keys(res.data.dataList).forEach(key=>{
                localUsedDatabase[key]=res.data.dataList[key]
              })
            } else {
              proxy.$modal.alertError(res.message)
            }
          })
        })
      })
  
    } else {
      proxy.$modal.alert("暂不支持此连接！");
    }
  }


/**
 *打开连接
 */
export function openConnect(proxy,connect) {
    let channel = '';
    switch (connect.connectId) {
        case 1:
            channel = proxy.$ipcRouters.mysqlMng.showDataBase;
            break;
        default:
            break;
    }
    if (channel.length > 0) {
        proxy.$userIpc.invoke(channel, connect).then(res => {
            let row = {}
            if (res.code === 200) {
                row.usedDatabase = []
                res.data.dataList.forEach(item => {
                    let localRow = {}
                    Object.keys(item).forEach(key=>{
                        localRow[key.toLowerCase()] =item[key]
                    })
                    localRow.tableList = []
                    row.usedDatabase.push(localRow)
                })
                proxy.$appStore.setUsedConnect(connect.id,row)
            } else {
                proxy.$modal.alertError(res.message)
            }
        })

    } else {
        proxy.$modal.alert("暂不支持此连接！");
    }
}

/**
 * 关闭连接
 */
export function closeConnect(proxy,connect) {
    proxy.$appStore.setUsedConnect(connect.id,null)
}

function getLocalConnect(connect, databaseName) {
    let localConnect = {}
    localConnect.host = connect.host
    localConnect.port = connect.port
    localConnect.username = connect.username
    localConnect.password = connect.password
    localConnect.database = databaseName
    return localConnect
}

/***
 * 打开数据库
 * */
export function openDatabase(proxy,connect, databaseName) {
    let channel = '';
    switch (connect.connectId) {
        case 1:
            channel = proxy.$ipcRouters.mysqlMng.showDatabaseTables;
            break;
        default:
            break;
    }
    if (channel && channel.length > 0) {
        let localConnect = getLocalConnect(connect, databaseName)
        let params={databaseKey:databaseName}
        proxy.$userIpc.invoke(channel, localConnect,params).then(res => {
            if (res.code === 200) {
                proxy.$appStore.usedConnect[connect.id]?.usedDatabase.forEach(selectDataBase=>{
                    if(selectDataBase.schema_name===databaseName){
                        selectDataBase.tableList=[]
                        selectDataBase.showTable=true
                        Object.keys(res.data).forEach(key=>{
                            selectDataBase[key]=res.data[key]
                        })
                    }
                })
            } else {
                proxy.$modal.alertError(res.message)
            }
        })
    } else {
        proxy.$modal.alert("暂不支持此连接！");
    }
}
/***
 * 关闭数据库
 * */
export function closeDatabase(proxy,connect, databaseName) {
    let thisDatabaseInfo = proxy.$appStore.usedConnect[connect.id].usedDatabase.find(row=>row.schema_name===databaseName)
    thisDatabaseInfo.showTable=false
    thisDatabaseInfo.tableList=[]
}
/***
 * 删除连接
 * */
export function deleteConnect(proxy,connect) {
    proxy.$modal.confirm('是否确认删除当前连接？').then(function() {
        return proxy.$userIpc.invoke(proxy.$ipcRouters.connectManage.deleteConnect, connect);
    }).then(() => {
        refreshConnection(proxy)
        proxy.$modal.msgSuccess("删除成功");
    }).catch(() => {});

}
/***
 * 复制连接
 * */
export function cloneConnect(proxy,connect) {
    proxy.$modal.confirm('是否确认复制当前连接？').then(function() {
        return proxy.$userIpc.invoke(proxy.$ipcRouters.connectManage.cloneConnect, connect);
    }).then(() => {
        refreshConnection(proxy)
        proxy.$modal.msgSuccess("复制成功");
    }).catch(() => {});
}
/***
 * 查询数据库表
 * */
export function queryTableList(proxy,connect,databaseName,options) {
    let localConnect = getLocalConnect(connect, databaseName)
    let params={databaseKey:databaseName}
    proxy.$userIpc.invoke(proxy.$ipcRouters.mysqlMng.selectTableList, localConnect,params).then(res => {
        if (res.code === 200) {
            res.data?.dataList.forEach(item=>options.push(toLowerCaseKey(item)))
        } else {
            proxy.$modal.alertError(res.message)
        }
    })
}

/***
 * 查询数据库表
 * */
export function queryTableFields(proxy,connect,databaseName,tableName) {
  return   proxy.$userIpc.invoke(proxy.$ipcRouters.mysqlMng.selectTableFields, connect,{databaseKey:databaseName,tableKey:tableName})
}

/**
 * 查询表引擎
 * @param proxy
 * @param connect
 * @param options
 */
export function queryTableEngines(proxy,connect,options) {
    proxy.$userIpc.invoke(proxy.$ipcRouters.mysqlMng.selectTableEngines, connect).then(res => {
        if (res.code === 200) {
            res.data?.dataList.forEach(item=>options.push(toLowerCaseKey(item)))
        } else {
            proxy.$modal.alertError(res.message)
        }
    })
}

/**
 *
 * @param proxy
 * @param connect
 * @param databaseName
 * @param tableName
 * @param options
 */
export function queryTableDataList(proxy,connect,databaseName,tableName,options) {
    let localConnect = getLocalConnect(connect, databaseName)
    let params={databaseKey:databaseName,tableKey:tableName}
    proxy.$userIpc.invoke(proxy.$ipcRouters.mysqlMng.selectTableDataList, localConnect,params).then(res => {
        if (res.code === 200) {
            res.data?.dataList.forEach(item=>options.push(toLowerCaseKey(item)))
        } else {
            proxy.$modal.alertError(res.message)
        }
    })
}

export function queryTableDataPageList(proxy,connect,params) {
    let localConnect = getLocalConnect(connect, params.databaseName)
    return proxy.$userIpc.invoke(proxy.$ipcRouters.mysqlMng.selectTableDataPageList, localConnect,params)
}

